<?php
/**
 * Created by PhpStorm.
 * User: 鄢鹏权
 * Date: 2017/7/26
 * Time: 21:08
 */
$path = isset($argv[1])&&$argv[1]?$argv[1]:'Public/PC';
$js = isset($argv[2])&&$argv[2]?$argv[2]:'Public/html.js';
if(is_dir($path)){
    generate_htmljs($path,$js);
}else{
    echo '';
}
function each_dir($dir,callable $dir_callback=null,callable $file_callback=null){
    if(is_dir($dir)){
        foreach (scandir($dir) as $path){
            if(!in_array($path, ['.','..'])){
                $path = $dir.DIRECTORY_SEPARATOR.$path;
                $path = str_replace("\\",'/',$path);
                $path = str_replace("//",'/',$path);
                if(is_dir($path)){
                    if(is_callable($dir_callback)&&false===call_user_func($dir_callback,$path)){
//                        call_user_func($dir_callback,$path);
                        return false;
                    }
                    each_dir($path, $dir_callback, $file_callback);
                }else{
                    if(is_callable($file_callback)&&false===call_user_func($file_callback,$path)){
//                        call_user_func($file_callback,$path);
                        return false;
                    }
                }
            }
        }
    }
}

function generate_htmljs($HTMLDir,$OutputJS){
    $HTMLMap=[];
    $Path = $HTMLDir;
    if(substr($Path,-1)!='/')$Path.='/';
    each_dir($Path,null,function ($path)use(&$HTMLMap,$Path){
        if(substr($path,-5)=='.html'){
            $Content = str_replace([
                '  ',"\r\n",
            ],' ',file_get_contents($path));
            $path = str_replace($Path,'',$path);
            $pathInfo = pathinfo($path);
            $Dir =$Obj=$Type= '';
            if($pathInfo['dirname']){
                $Dir=$pathInfo['dirname'];
            }
            list($Obj,$Type)=explode('_',$pathInfo['filename']);
            $HTMLMap[$Dir][$Obj][$Type]=$Content;
        }
    });
    $JSONStr = json_encode($HTMLMap,JSON_UNESCAPED_UNICODE);
    file_put_contents($OutputJS,"Config.HTMLMap = ".$JSONStr.";");
}